<template>
    <div class="app-container">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="量表编号" prop="number">
          <el-input
            v-model="queryParams.number"
            placeholder="请输入量表编号"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="量表名称" prop="name">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入量表名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="简称" prop="shortName">
          <el-input
            v-model="queryParams.shortName"
            placeholder="请输入简称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="指标名称" prop="evaluation">
          <el-input
            v-model="queryParams.evaluation"
            placeholder="请输入指标名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="queryParams.type" placeholder="请选择类型" clearable>
            <el-option label="积极" :value="1" />
            <el-option label="消极" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
  
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['system:table:add']"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['system:table:edit']"
          >修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:table:remove']"
          >删除</el-button>
        </el-col>

        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-document"
            size="mini"
            @click="downloadScaleTemplate"
          >下载模板</el-button>
        </el-col>

        <el-col :span="1.5">
          <el-button
            type="info"
            plain
            icon="el-icon-upload2"
            size="mini"
            @click="handleImport"
          >导入</el-button>
        </el-col>
        
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
  
      <el-table v-loading="loading" :data="tableList" @selection-change="handleSelectionChange" border stripe highlight-current-row class="scale-main-table">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="量表编号" align="center" prop="id" min-width="60" show-overflow-tooltip />
        <el-table-column label="量表名称" align="center" prop="name" min-width="120" show-overflow-tooltip />
        <el-table-column label="简称" align="center" prop="shortName" min-width="100" show-overflow-tooltip />
        <el-table-column label="指标名称" align="center" prop="evaluation" min-width="120" show-overflow-tooltip />
        <el-table-column label="积分方式" align="center" min-width="100">
          <template slot-scope="scope">
            {{ scope.row.pointsType === '0' || scope.row.pointsType === 0 ? '总分' : '平均分' }}
          </template>
        </el-table-column>
        <el-table-column label="类型" align="center" min-width="80">
          <template slot-scope="scope">
            {{ scope.row.type === '1' || scope.row.type === 1 ? '积极' : '消极' }}
          </template>
        </el-table-column>
        <el-table-column label="指导语" align="center" prop="introduce" min-width="200" show-overflow-tooltip />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="230">
          <template slot-scope="scope">
            <el-button
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['system:table:edit']"
            >修改</el-button>
            <el-button
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['system:table:remove']"
            >删除</el-button>
            <el-button
              type="text"
              icon="el-icon-view"
              @click="handleView(scope.row)"
            >查看</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
  
      <!-- 添加或修改量表对话框 -->
      <el-drawer
        :title="title"
        :visible.sync="openDrawer"
        direction="rtl"
        size="90%"
        :before-close="handleDrawerClose"
        append-to-body
        class="scale-drawer"
      >
        <div class="drawer-container">
          <el-tabs v-model="activeTab" type="border-card">
            <el-tab-pane label="基本属性" name="basic">
              <el-form ref="form" :model="form" :rules="rules" label-width="100px" class="scale-form">
                <el-card shadow="hover" class="scale-card">
                  <div slot="header" class="card-header">
                    <span>量表基本信息</span>
                  </div>
                  <el-row :gutter="20">
                    <el-col :span="12">
                      <el-form-item label="量表名称" prop="name">
                        <el-input v-model="form.name" placeholder="请输入量表名称" clearable />
          </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="类型" prop="type">
                        <el-radio-group v-model="form.type">
                          <el-radio label="1">积极</el-radio>
                          <el-radio label="2">消极</el-radio>
                        </el-radio-group>
          </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row :gutter="20">
                    <el-col :span="12">
                      <el-form-item label="简称" prop="shortName">
                        <el-input v-model="form.shortName" placeholder="请输入简称" clearable />
          </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="指标名称" prop="evaluation">
                        <el-input v-model="form.evaluation" placeholder="请输入指标名称" clearable />
          </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row :gutter="20">
                    <el-col :span="24">
                      <el-form-item label="积分方式" prop="pointsType">
                        <el-radio-group v-model="form.pointsType">
                          <el-radio label="总分">总分</el-radio>
                          <el-radio label="平均分">平均分</el-radio>
                        </el-radio-group>
          </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row :gutter="20">
                    <el-col :span="24">
                      <el-form-item label="定义" prop="number">
                        <el-input v-model="form.number" type="textarea" :rows="2" placeholder="请输入量表定义" />
          </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row :gutter="20">
                    <el-col :span="24">
                      <el-form-item label="指导语" prop="introduce">
                        <el-input v-model="form.introduce" type="textarea" :rows="3" placeholder="请输入指导语" />
          </el-form-item>
                    </el-col>
                  </el-row>
                </el-card>
        </el-form>
            </el-tab-pane>
            
            <el-tab-pane label="测评等级" name="levels">
              <el-card shadow="hover" class="scale-card">
                <div slot="header" class="card-header">
                  <span>测评等级设置</span>
                  <el-button type="primary" size="mini" icon="el-icon-plus" @click="addLevel">新增等级</el-button>
                </div>
                <el-table :data="form.levels || []" border stripe highlight-current-row class="scale-table">
                  <el-table-column label="行为名称" prop="name" width="180">
                    <template slot-scope="scope">
                      <el-input v-model="scope.row.name" placeholder="请输入行为名称" />
                    </template>
                  </el-table-column>
                  <el-table-column label="测评结果描述" prop="description">
                    <template slot-scope="scope">
                      <el-input type="textarea" v-model="scope.row.description" :rows="3" placeholder="请输入测评结果描述" />
                    </template>
                  </el-table-column>
                  <el-table-column label="测评结果等级" prop="level" width="150">
                    <template slot-scope="scope">
                      <el-select v-model="scope.row.level" placeholder="请选择等级">
                        <el-option label="正常" value="正常" />
                        <el-option label="轻度" value="轻度" />
                        <el-option label="中度" value="中度" />
                        <el-option label="重度" value="重度" />
                      </el-select>
                    </template>
                  </el-table-column>
                  <el-table-column label="最低分" prop="minScore" width="100">
                    <template slot-scope="scope">
                      <el-input-number v-model="scope.row.minScore" :min="0" :max="100" controls-position="right" :precision="2" style="width: 100px;" />
                    </template>
                  </el-table-column>
                  <el-table-column label="能否低于最低分" prop="canBeLower" width="150">
                    <template slot-scope="scope">
                      <el-switch
                        v-model="scope.row.canBeLower"
                        active-text="是"
                        inactive-text="否"
                        active-color="#13ce66"
                        inactive-color="#ff4949">
                      </el-switch>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="80">
                    <template slot-scope="scope">
                      <el-button type="text" icon="el-icon-delete" @click="removeLevel(scope.$index)" class="red-icon">删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
                <div v-if="(form.levels || []).length === 0" class="empty-levels">
                  <i class="el-icon-data-analysis"></i>
                  <p>暂无等级数据，请点击"新增等级"按钮添加</p>
                </div>
              </el-card>
            </el-tab-pane>
            
            <el-tab-pane label="问题和选项" name="questions">
              <el-card shadow="hover" class="scale-card">
                <div slot="header" class="card-header">
                  <span>问题设置</span>
                  <el-button type="primary" size="mini" icon="el-icon-plus" @click="addQuestion">新增问题</el-button>
                </div>
                <div v-for="(question, qIndex) in form.questions || []" :key="'q-'+qIndex" class="question-item">
                  <div class="question-header">
                    <span class="question-index">题目 {{qIndex + 1}}</span>
                    <el-button type="danger" size="mini" icon="el-icon-delete" plain @click="removeQuestion(qIndex)">删除</el-button>
                  </div>
                  <el-input v-model="question.content" type="textarea" :rows="2" placeholder="请输入问题内容" />
                  <div class="question-type-selector">
                    <el-select v-model="question.type" placeholder="请选择题目类型" size="small" style="width: 120px;">
                      <el-option label="单选题" value="single"></el-option>
                      <el-option label="多选题" value="multiple"></el-option>
                    </el-select>
                  </div>
                  <div class="option-container">
                    <div class="option-header">
                      <span class="option-title">选项设置</span>
                      <el-button type="primary" size="mini" icon="el-icon-plus" plain @click="addOption(qIndex)">新增选项</el-button>
                    </div>
                    <el-table :data="question.options || []" border stripe class="scale-table">
                      <el-table-column label="选项内容" prop="content">
                        <template slot-scope="scope">
                          <el-input 
                            type="textarea" 
                            v-model="scope.row.content" 
                            :rows="2" 
                            maxlength="100"
                            show-word-limit
                            resize="none"
                            placeholder="请输入选项内容" 
                            style="width: 100%; min-width: 150px;" />
                        </template>
                      </el-table-column>
                      <el-table-column label="分值" width="100">
                        <template slot-scope="scope">
                          <el-input-number v-model="scope.row.score" :min="0" :max="10" controls-position="right" :precision="2" style="width: 100px;" />
                        </template>
                      </el-table-column>
                      <el-table-column label="操作" width="80">
                        <template slot-scope="scope">
                          <el-button type="text" icon="el-icon-delete" @click="removeOption(qIndex, scope.$index)" class="red-icon">删除</el-button>
                        </template>
                      </el-table-column>
                    </el-table>
                  </div>
                </div>
                <div v-if="(form.questions || []).length === 0" class="empty-questions">
                  <i class="el-icon-document"></i>
                  <p>暂无问题，请点击"新增问题"按钮添加</p>
                </div>
              </el-card>
            </el-tab-pane>
          </el-tabs>
          <div class="drawer-footer">
            <el-button type="primary" @click="submitForm" icon="el-icon-check">确 定</el-button>
            <el-button @click="closeDrawer" icon="el-icon-close">取 消</el-button>
          </div>
        </div>
      </el-drawer>

      <!-- 查看量表详情对话框 -->
      <el-drawer
        title="查看量表详情"
        :visible.sync="viewOpen"
        direction="rtl"
        size="90%"
        :before-close="handleViewDrawerClose"
        append-to-body
        class="scale-drawer"
      >
        <div class="drawer-container">
          <el-tabs v-model="viewActiveTab" type="border-card">
            <el-tab-pane label="基本属性" name="basic">
              <el-card shadow="hover" class="scale-card">
                <div slot="header" class="card-header">
                  <span>基本信息</span>
                </div>
                <el-descriptions :column="2" border>
                  <el-descriptions-item label="量表编号" :span="1">{{ viewForm.id }}</el-descriptions-item>
                  <el-descriptions-item label="量表名称" :span="1">{{ viewForm.name }}</el-descriptions-item>
                  <el-descriptions-item label="简称" :span="1">{{ viewForm.shortName }}</el-descriptions-item>
                  <el-descriptions-item label="指标名称" :span="1">{{ viewForm.evaluation }}</el-descriptions-item>
                  <el-descriptions-item label="积分方式" :span="1">
                    {{ viewForm.pointsType === '0' || viewForm.pointsType === 0 ? '总分' : '平均分' }}
                  </el-descriptions-item>
                  <el-descriptions-item label="类型" :span="1">
                    {{ viewForm.type === '1' || viewForm.type === 1 ? '积极' : '消极' }}
                  </el-descriptions-item>
                  <el-descriptions-item label="定义" :span="2">{{ viewForm.name || '-' }}</el-descriptions-item>
                  <el-descriptions-item label="指导语" :span="2">{{ viewForm.introduce || '-' }}</el-descriptions-item>
                </el-descriptions>
              </el-card>
            </el-tab-pane>
            
            <el-tab-pane label="测评等级" name="levels">
              <el-card shadow="hover" class="scale-card">
                <div slot="header" class="card-header">
                  <span>测评等级列表</span>
                </div>
                <el-table v-if="viewForm.levels && viewForm.levels.length > 0" :data="viewForm.levels" border stripe class="scale-table">
                  <el-table-column label="行为名称" prop="name" min-width="120" show-overflow-tooltip />
                  <el-table-column label="测评结果描述" prop="description" min-width="180" show-overflow-tooltip />
                  <el-table-column label="测评结果等级" prop="level" width="100" align="center" />
                  <el-table-column label="最低分" prop="minScore" width="80" align="center" />
                  <el-table-column label="能否低于最低分" width="120" align="center">
                    <template slot-scope="scope">
                      <el-tag :type="scope.row.canBeLower ? 'success' : 'info'">
                        {{ scope.row.canBeLower ? '是' : '否' }}
                      </el-tag>
                    </template>
                  </el-table-column>
                </el-table>
                <div v-else class="empty-data">
                  <i class="el-icon-document"></i>
                  <p>暂无测评等级数据</p>
                </div>
              </el-card>
            </el-tab-pane>
            
            <el-tab-pane label="问题和选项" name="questions">
              <el-card shadow="hover" class="scale-card">
                <div slot="header" class="card-header">
                  <span>问题列表</span>
                </div>
                <div v-if="viewForm.questions && viewForm.questions.length > 0">
                  <div v-for="(question, qIndex) in viewForm.questions" :key="'vq-'+qIndex" class="view-question-item">
                    <div class="question-title">
                      <el-tag type="primary">题目 {{qIndex + 1}}</el-tag>
                      <span class="question-content">{{ question.content }}</span>
                      <el-tag size="small" effect="plain" type="success" v-if="question.type === 'single'" style="margin-left: 10px;">单选题</el-tag>
                      <el-tag size="small" effect="plain" type="warning" v-else-if="question.type === 'multiple'" style="margin-left: 10px;">多选题</el-tag>
                    </div>
                    <el-table v-if="question.options && question.options.length > 0" :data="question.options" border stripe class="scale-table">
                      <el-table-column label="选项序号" width="80" align="center">
                        <template slot-scope="scope">
                          {{ scope.$index + 1 }}
                        </template>
                      </el-table-column>
                      <el-table-column label="选项内容" prop="content" min-width="180">
                        <template slot-scope="scope">
                          <div style="white-space: pre-wrap; line-height: 1.5;">{{ scope.row.content }}</div>
                        </template>
                      </el-table-column>
                      <el-table-column label="分值" prop="score" width="80" align="center" />
                    </el-table>
                    <div v-else class="empty-options">暂无选项数据</div>
                  </div>
                </div>
                <div v-else class="empty-data">
                  <i class="el-icon-document"></i>
                  <p>暂无问题数据</p>
                </div>
              </el-card>
            </el-tab-pane>
          </el-tabs>
          <div class="drawer-footer">
            <el-button @click="closeViewDrawer" icon="el-icon-close">关 闭</el-button>
          </div>
        </div>
      </el-drawer>

      <!-- 量表导入对话框 -->
      <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
        <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" 
          :action="upload.url" 
          :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" 
          :on-success="handleFileSuccess" :auto-upload="false" drag>
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip text-center" slot="tip">
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline" @click="downloadScaleTemplate">下载模板</el-link>
          </div>
        </el-upload>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import { listTable, getTable, delTable, addTable, updateTable } from "@/api/system/table";
  import * as XLSX from 'xlsx';
  import FileSaver from 'file-saver';
  import { getToken } from "@/utils/auth";
  export default {
    name: "Table",
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 量表表格数据
        tableList: [],
        // 弹出层标题
        title: "",
        // 是否显示抽屉
        openDrawer: false,
        // 是否显示查看弹出层
        viewOpen: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          number: null,
          pointsType: null,
          evaluation: null,
          shortName: null,
          name: null,
          introduce: null,
          tableCreator: null,
          taskLevelIds: null,
          questionIds: null,
          type: null
        },
        // 表单参数
        form: {},
        // 查看表单参数
        viewForm: {},
        // 表单校验
        rules: {
          number: [
            { required: true, message: "量表编号不能为空", trigger: "blur" }
          ],
          name: [
            { required: true, message: "量表名称不能为空", trigger: "blur" }
          ],
          shortName: [
            { required: true, message: "简称不能为空", trigger: "blur" }
          ],
          evaluation: [
            { required: true, message: "指标名称不能为空", trigger: "blur" }
          ],
          pointsType: [
            { required: true, message: "积分方式不能为空", trigger: "change" }
          ],
          introduce: [
            { required: true, message: "指导语不能为空", trigger: "blur" }
          ],
          type: [
            { required: true, message: "类型不能为空", trigger: "change" }
          ]
        },
        activeTab: 'basic',
        viewActiveTab: 'basic',
        
        // 量表模板上传参数
        upload: {
          // 是否显示弹出层（量表导入）
          open: false,
          // 弹出层标题（量表导入）
          title: "量表导入",
          // 是否禁用上传
          isUploading: false,
          // 设置上传的请求头部
          headers: { Authorization: "Bearer " + getToken() },
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/system/table/import"
        },
      };
    },
    created() {
      this.getList();
    },
    methods: {
      downloadScaleTemplate() {
        this.exportRobotsTxt()
      },
      handleViewQuestionnaire(row) {
        this.$router.push({
          path: '/questionnaireLogRoute',
          query: { id: row.id }
        });
      },
      /** 导出robots.txt文件 */
      exportRobotsTxt() {
        const robotsUrl = process.env.BASE_URL + '1.xlsx';
        
        fetch(robotsUrl)
          .then(response => response.blob())
          .then(blob => {
            const url = window.URL.createObjectURL(blob);
            const aLink = document.createElement('a');
            document.body.appendChild(aLink);
            aLink.href = url;
            aLink.download = '模板.xlsx';
            aLink.click();
            window.URL.revokeObjectURL(url);
            aLink.remove();
            
            this.$message({
              message: '模板导出成功',
              type: 'success',
              duration: 1500
            });
          })
          .catch(error => {
            this.$message.error('导出失败: ' + error.message);
          });
      },
      /** 查询量表列表 */
      getList() {
        this.loading = true;
        listTable(this.queryParams).then(response => {
          this.tableList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.openDrawer = true;
        this.title = "添加量表";
        this.form.levels = [];
        
        // 添加默认问题和选项
        this.form.questions = [
          {
            content: "",
            type: "single",
            options: []
          }
        ];
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids
        getTable(id).then(response => {
          this.form = response.data;
          console.log('获取到的原始数据:', JSON.stringify(this.form));
          console.log('原始type值:', this.form.type, typeof this.form.type);
          
          // 确保type是字符串类型
          if (this.form.type !== null && this.form.type !== undefined) {
            this.form.type = String(this.form.type);
            console.log('处理后的表单type值:', this.form.type, typeof this.form.type);
          } else {
            this.form.type = "1"; // 默认设置为积极
            console.log('设置默认type值:', this.form.type, typeof this.form.type);
          }
          
          // 确保积分方式的值是字符串类型
          if (this.form.pointsType !== null && this.form.pointsType !== undefined) {
            this.form.pointsType = String(this.form.pointsType);
            // 映射积分方式的值
            if (this.form.pointsType === "0") {
              this.form.pointsType = "总分";
            } else if (this.form.pointsType === "1") {
              this.form.pointsType = "平均分";
            }
          }
          
          // 处理taskLevelIds（测评等级）数据 - 将JSON字符串转为对象
          if (this.form.taskLevelIds && typeof this.form.taskLevelIds === 'string') {
            try {
              console.log('原始taskLevelIds:', this.form.taskLevelIds);
              const parsedLevels = JSON.parse(this.form.taskLevelIds);
              console.log('解析后的parsedLevels:', parsedLevels);
              
              this.form.levels = parsedLevels.map(level => {
                console.log('处理level项:', level);
                return {
                  name: level.name || '',
                  description: level.detail || '',
                  level: level.level || '',
                  minScore: level.lowestScore !== undefined ? Number(level.lowestScore) : 0,
                  canBeLower: level.isLowestScore === true
                }
              });
              console.log('映射后的等级数据:', this.form.levels);
            } catch (e) {
              console.error('解析测评等级数据失败', e);
              this.form.levels = [];
            }
          } else {
            this.form.levels = [];
          }
          
          // 处理questionIds（问题选项）数据 - 将JSON字符串转为对象
          if (this.form.questionIds && typeof this.form.questionIds === 'string') {
            try {
              const parsedQuestions = JSON.parse(this.form.questionIds);
              this.form.questions = parsedQuestions.map(q => {
                return {
                  content: q.name || '',
                  type: q.type || 'single',
                  options: (q.options || []).filter(o => o && o.name !== undefined).map(o => {
                    return {
                      content: o.name || '',
                      score: o.score || 0
                    }
                  })
                }
              });
            } catch (e) {
              console.error('解析问题选项数据失败', e);
              this.form.questions = [];
            }
          } else {
            this.form.questions = [];
          }
          
          this.openDrawer = true;
          this.title = "修改量表";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            // 处理提交的数据，将对象转为JSON字符串
            const submitForm = { ...this.form };
            
            // 处理积分方式的值转换
            if (submitForm.pointsType === '总分') {
              submitForm.pointsType = '0';
            } else if (submitForm.pointsType === '平均分') {
              submitForm.pointsType = '1';
            }
            
            // 确保type是数字
            if (submitForm.type !== null && submitForm.type !== undefined) {
              submitForm.type = Number(submitForm.type);
              console.log('提交时转换的type:', submitForm.type, typeof submitForm.type);
            }
            
            // 将测评等级数据转换为JSON字符串
            if (submitForm.levels && submitForm.levels.length > 0) {
              console.log('提交前的levels数据:', submitForm.levels);
              submitForm.taskLevelIds = JSON.stringify(submitForm.levels.map(level => {
                return {
                  name: level.name || '',
                  detail: level.description || '',
                  level: level.level || '',
                  lowestScore: level.minScore !== undefined ? level.minScore : 0,
                  isLowestScore: level.canBeLower === true
                }
              }));
              console.log('转换后的taskLevelIds:', submitForm.taskLevelIds);
            } else {
              submitForm.taskLevelIds = '[]';
            }
            
            // 将问题选项数据转换为JSON字符串
            if (submitForm.questions && submitForm.questions.length > 0) {
              console.log('提交前的questions数据:', submitForm.questions);
              submitForm.questionIds = JSON.stringify(submitForm.questions.map(q => {
                return {
                  name: q.content || '',
                  type: q.type || 'single',
                  options: (q.options || []).map(o => {
                    return {
                      name: o.content || '',
                      score: o.score || 0
                    }
                  })
                }
              }));
              console.log('转换后的questionIds:', submitForm.questionIds);
            } else {
              submitForm.questionIds = '[]';
            }
  
            delete submitForm.levels;
            delete submitForm.questions;
            
            if (this.form.id != null) {
              updateTable(submitForm).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.openDrawer = false;
                this.getList();
              });
            } else {
              addTable(submitForm).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.openDrawer = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 取消按钮 */
      cancel() {
        this.handleDrawerClose(() => {
          this.openDrawer = false;
        });
      },
      /** 处理抽屉关闭前的询问 */
      handleDrawerClose(done) {
        this.$confirm('确认关闭？未保存的内容将会丢失', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.reset();
          done();
        }).catch(() => {
          // 用户取消关闭，不执行任何操作
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm('是否确认删除量表编号为"' + ids + '"的数据项？').then(function() {
          return delTable(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('system/table/export', {
          ...this.queryParams
        }, `table_${new Date().getTime()}.xlsx`)
      },
      /** 前端导出当前页数据 */
      exportCurrentPage() {
        if (this.tableList.length === 0) {
          this.$message({
            message: '当前没有数据可导出',
            type: 'warning'
          });
          return;
        }

        // 定义要导出的列和对应的表头
        const columns = [
          { key: 'id', title: '量表编号', width: 15 },
          { key: 'name', title: '量表名称', width: 20 },
          { key: 'shortName', title: '简称', width: 15 },
          { key: 'evaluation', title: '指标名称', width: 20 },
          { key: 'pointsType', title: '积分方式', width: 10 },
          { key: 'introduce', title: '指导语', width: 30 }
        ];
        
        // 处理数据，特别是积分方式需要进行转换
        const exportData = this.tableList.map(row => {
          const item = {};
          columns.forEach(col => {
            if (col.key === 'pointsType') {
              item[col.title] = row[col.key] === '0' || row[col.key] === 0 ? '总分' : '平均分';
            } else {
              item[col.title] = row[col.key] || '';
            }
          });
          return item;
        });
        
        // 创建工作表
        const worksheet = XLSX.utils.json_to_sheet(exportData);
        
        // 设置列宽
        const columnWidths = columns.map(col => ({ wch: col.width }));
        worksheet['!cols'] = columnWidths;
        
        // 创建工作簿
        const workbook = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(workbook, worksheet, '量表数据');
        
        // 设置导出文件名
        const timestamp = new Date().toLocaleDateString().replace(/\//g, '-') + 
                         '_' + new Date().toLocaleTimeString().replace(/:/g, '-').replace(/\s/g, '');
        const fileName = `量表数据_${timestamp}.xlsx`;
        
        // 导出文件
        const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
        const blob = new Blob([excelBuffer], { type: 'application/octet-stream' });
        FileSaver.saveAs(blob, fileName);
        
        this.$message({
          message: '导出成功',
          type: 'success',
          duration: 1500
        });
      },
      /** 查看按钮操作 */
      handleView(row) {
        this.viewForm = {};
        this.viewActiveTab = 'basic';
        const id = row.id || this.ids;
        getTable(id).then(response => {
          this.viewForm = response.data;
          
          // 处理taskLevelIds（测评等级）数据 - 将JSON字符串转为对象
          if (this.viewForm.taskLevelIds && typeof this.viewForm.taskLevelIds === 'string') {
            try {
              const parsedLevels = JSON.parse(this.viewForm.taskLevelIds);
              this.viewForm.levels = parsedLevels.map(level => {
                return {
                  name: level.name || '',
                  description: level.detail || '',
                  level: level.level || '',
                  minScore: level.lowestScore || 0,
                  canBeLower: level.isLowestScore || false
                };
              });
            } catch (e) {
              console.error('解析测评等级数据失败', e);
              this.viewForm.levels = [];
            }
          } else {
            this.viewForm.levels = [];
          }
          
          // 处理questionIds（问题选项）数据 - 将JSON字符串转为对象
          if (this.viewForm.questionIds && typeof this.viewForm.questionIds === 'string') {
            try {
              const parsedQuestions = JSON.parse(this.viewForm.questionIds);
              this.viewForm.questions = parsedQuestions.map(q => {
                return {
                  content: q.name || '',
                  type: q.type || 'single',
                  options: (q.options || []).filter(o => o && o.name !== undefined).map(o => {
                    return {
                      content: o.name || '',
                      score: o.score || 0
                    }
                  })
                }
              });
            } catch (e) {
              console.error('解析问题选项数据失败', e);
              this.viewForm.questions = [];
            }
          } else {
            this.viewForm.questions = [];
          }
          
          this.viewOpen = true;
        });
      },
      addLevel() {
        if (!this.form.levels) {
          this.$set(this.form, 'levels', []);
        }
        this.form.levels.push({
          name: '',
          description: '',
          level: '正常',
          minScore: 0,
          canBeLower: false
        });
      },
      removeLevel(index) {
        this.form.levels.splice(index, 1);
      },
      addQuestion() {
        if (!this.form.questions) {
          this.$set(this.form, 'questions', []);
        }
        this.form.questions.push({
          content: '',
          type: 'single',
          options: []
        });
      },
      removeQuestion(index) {
        this.form.questions.splice(index, 1);
      },
      addOption(questionIndex) {
        if (!this.form.questions[questionIndex].options) {
          this.$set(this.form.questions[questionIndex], 'options', []);
        }
        this.form.questions[questionIndex].options.push({
          content: '',
          score: 0
        });
      },
      removeOption(questionIndex, optionIndex) {
        this.form.questions[questionIndex].options.splice(optionIndex, 1);
      },
      reset() {
        this.form = {
          id: null,
          number: null,
          pointsType: "总分",
          evaluation: null,
          shortName: null,
          name: null,
          introduce: null,
          definition: null,
          tableCreator: null,
          type: "1",
          levels: [],
          questions: [],
        };
        this.resetForm("form");
      },
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length!==1
        this.multiple = !selection.length
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      /** 处理查看抽屉关闭前的询问 */
      handleViewDrawerClose(done) {
        this.$confirm('确认关闭查看窗口?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'info'
        }).then(() => {
          done();
        }).catch(() => {
          // 用户取消关闭，不执行任何操作
        });
      },
      /** 直接关闭编辑抽屉 */
      closeDrawer() {
        this.handleDrawerClose(() => {
          this.openDrawer = false;
        });
      },
      /** 直接关闭查看抽屉 */
      closeViewDrawer() {
        this.handleViewDrawerClose(() => {
          this.viewOpen = false;
        });
      },
      /** 导入按钮操作 */
      handleImport() {
        this.upload.open = true;
      },
      
      // 文件上传中处理
      handleFileUploadProgress(event, file, fileList) {
        this.upload.isUploading = true;
      },
      
      // 文件上传成功处理
      handleFileSuccess(response, file, fileList) {
        this.upload.open = false;
        this.upload.isUploading = false;
        this.$refs.upload.clearFiles();
        this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
        this.getList();
      },
      
      // 提交上传文件
      submitFileForm() {
        this.$refs.upload.submit();
      },
    }
  };
  </script>
  
  <style scoped>
  .app-container {
    padding: 20px;
  }

  .scale-main-table {
    margin-top: 15px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  }

  .scale-main-table .el-button {
    padding: 5px 10px;
    margin: 0 3px;
  }

  .level-container, .question-container {
    margin-top: 10px;
  }
  
  .level-header, .question-header, .option-header {
    margin-bottom: 15px;
    display: flex;
    justify-content: flex-start;
  }
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .scale-card {
    margin-bottom: 20px;
  }
  
  .scale-form .el-form-item {
    margin-bottom: 18px;
  }
  
  .scale-table {
    margin-top: 10px;
  }
  
  .question-item {
    margin-bottom: 25px;
    padding: 15px;
    border: 1px solid #ebeef5;
    border-radius: 5px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
    background-color: #ffffff;
  }
  
  .view-question-item {
    margin-bottom: 20px;
    padding: 15px;
    border: 1px solid #ebeef5;
    border-radius: 5px;
    background-color: #f9f9f9;
  }
  
  .question-title {
    margin-bottom: 15px;
    font-size: 14px;
    line-height: 1.5;
    display: flex;
    align-items: center;
  }
  
  .question-content {
    margin-left: 10px;
    line-height: 20px;
  }
  
  .question-index {
    font-size: 16px;
    font-weight: bold;
    margin-right: 15px;
    line-height: 32px;
    color: #409EFF;
  }
  
  .question-header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 15px;
    align-items: center;
  }
  
  .option-container {
    margin-top: 15px;
    padding: 15px;
    background-color: #f8f8f8;
    border-radius: 4px;
  }
  
  .option-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
  }
  
  .option-title {
    font-size: 14px;
    font-weight: bold;
    color: #606266;
  }
  
  .el-tab-pane {
    max-height: 500px;
    overflow-y: auto;
    padding: 5px;
  }
  
  .red-icon {
    color: #F56C6C;
  }
  
  .empty-questions {
    text-align: center;
    padding: 30px 0;
    color: #909399;
    background-color: #f9f9f9;
    border-radius: 4px;
  }
  
  .empty-questions i {
    font-size: 50px;
    margin-bottom: 10px;
  }
  
  .scale-drawer :deep(.el-drawer__header) {
    padding: 15px 20px;
    margin-bottom: 0;
    border-bottom: 1px solid #e8e8e8;
    font-size: 18px;
    font-weight: bold;
  }
  
  .scale-drawer :deep(.el-drawer__body) {
    overflow-y: auto;
    padding: 0;
  }
  
  .scale-drawer :deep(.el-tabs__content) {
    max-height: calc(100vh - 200px);
    overflow-y: auto;
  }
  
  .drawer-container {
    height: 100%;
    padding: 20px;
    display: flex;
    flex-direction: column;
  }
  
  .drawer-footer {
    margin-top: 20px;
    text-align: center;
  }
  
  .empty-data {
    text-align: center;
    padding: 40px 0;
    color: #909399;
    background-color: #f9f9f9;
  }
  
  .empty-data i {
    font-size: 50px;
    margin-bottom: 10px;
  }
  
  .empty-options {
    text-align: center;
    padding: 15px;
    color: #909399;
    background-color: #f5f7fa;
    border-radius: 4px;
    font-size: 14px;
  }
  
  .empty-levels {
    text-align: center;
    padding: 30px 0;
    color: #909399;
    background-color: #f9f9f9;
    border-radius: 4px;
    margin-top: 15px;
  }
  
  .empty-levels i {
    font-size: 50px;
    margin-bottom: 10px;
  }

  .question-type-selector {
    margin: 10px 0;
    display: flex;
    align-items: center;
  }

  .question-type-selector::before {
    content: "题目类型:";
    font-size: 14px;
    color: #606266;
    margin-right: 10px;
  }
  </style>
  